import { Middleware, Context } from '@nuxt/types'

const authMiddleware: Middleware = async (context: Context) => {
  const path = context.route.path

  // 判断是服务端，并且已经登录才会获取用户数据
  if (typeof window === 'undefined') {
    const { cookie = '' } = context.req.headers
    // @ts-ignore
    if (cookie.includes(process.env.ADMIN_LOGIN)) {
      await context.store.dispatch('auth/SESSION_LOGIN')
    }
    // @ts-ignore
    if (cookie.includes(process.env.OAUTH_LOGIN)) {
      await context.store.dispatch('oauth/SESSION_LOGIN')
    }
  }
  if (path === '/login') {
    if (context.app.store!.getters['auth/IS_LOGIN']) {
      context.redirect('/admin')
    }
  } else if (path.indexOf('/admin') === 0) {
    if (!context.app.store!.getters['auth/IS_LOGIN']) {
      context.redirect('/login')
    }
  }
}

export default authMiddleware
